<template>
	<view class="page-body">
			<view class='wrapper'>
				<view>
					<input 	class="titleInput" 
							placeholder="标题..." 
							placeholder-style="font-style: italic"
							v-model="noteTitle"/>
				</view>
				
				<view class='toolbar' @tap="format" style="height: 40px; overflow-x :auto; padding: 1%;">
					
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold">
					</view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic">
					</view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
						data-name="underline"></view>
					<view class="iconfont icon-shanchu" @tap="clear"></view>
					<view class="iconfont icon-charutupian" @tap="insertImage"></view>
					<view class="iconfont icon-date" @tap="insertDate"></view>
					<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian"
						data-name="strike"></view>
					<!-- #ifndef MP-BAIDU -->
					<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi"
						data-name="align" data-value="left"></view>
					<!-- #endif -->
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi"
						data-name="align" data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
						data-name="align" data-value="right"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi"
						data-name="align" data-value="justify"></view>
					<!-- #ifndef MP-BAIDU -->
					<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height"
						data-name="lineHeight" data-value="2"></view>
					<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing"
						data-name="letterSpacing" data-value="2em"></view>
					<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju"
						data-name="marginTop" data-value="20px"></view>
					<view :class="formats.marginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju"
						data-name="marginBottom" data-value="20px"></view>
					<!-- #endif -->

					<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>

					<!-- #ifndef MP-BAIDU -->
					<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font"
						data-name="fontFamily" data-value="Pacifico"></view>
					<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize"
						data-name="fontSize" data-value="24px"></view>
					<!-- #endif -->
					<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color"
						data-name="color" data-value="#0000ff"></view>
					<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
						class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00"></view>
	
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie"
						data-name="list" data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
						data-name="list" data-value="bullet"></view>


					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1"
						data-name="header" :data-value="1"></view>
					<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao"
						data-name="script" data-value="sub"></view>
					<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao"
						data-name="script" data-value="super"></view>

					

					<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl"
						data-name="direction" data-value="rtl"></view>
				</view>
			
				<view>
					<image src="/static/tab-Icons/AI.png"
					   mode="widthFix"
					   style="width: 20%; position: fixed; top: 80%; left: 76%; z-index: 99;"
					   @click="AIAssistExpand">
					</image>
					<view class="searchBox" :class="{'active' : isActive}">
					<input placeholder="我有什么可以帮您的？" 
							placeholder-style="font-style: italic"
							@confirm="AIAssistAsk"
							v-model="AIAssistInput"/>
					</view>
				</view>
				
				<view class="editor-wrapper">
					<editor id="editor" 
							class="ql-container"
							:show-img-size="true" 
							:show-img-toolbar="true" 
							:show-img-resize="true" 
							placeholder="开始输入..." 
							@statuschange="onStatusChange" 
							:read-only="readOnly" 
							@ready="onEditorReady">
					</editor>
				</view>
				
				<view class="noteButton">
					<view class="iconfont icon-undo" @tap="undo" style="margin-left: 2%;"></view>
					<view class="iconfont icon-redo" style="margin-right: auto;" @tap="redo"></view>
					
					<image src="/static/tab-Icons/microphone.png" 
						   mode="widthFix"
						   style="width: 10%;"
						   @click="voiceDetectStart">
					</image>
					
					<image src="/static/tab-Icons/microphoneEnd.png"
						   mode="widthFix"
						   style="width: 10%; margin-right: 3%;"
						   @click="voiceDetectEnd">
					</image>
					
					<view>
						<button class="Btn" style="margin-bottom: 5%;" 
								@click = "saveNote">保存</button>
					</view>
					
					<view>
						
						<button class="Btn" style="margin-bottom: 5%;" 	
								@click = "publishNote(this.fileName, 3)">发布</button>
					</view>
				</view>
				

			</view>
		</view>
</template>

<script>
	import { generateRandomName } from '../../randomName';
	import config from '@/config.js';
	
	const recorderManager = uni.getRecorderManager();
	const options = {
	    duration: 30000,//指定录音的时长，单位 ms
	    sampleRate: 16000,//采样率
	    numberOfChannels: 1,//录音通道数
	    encodeBitRate: 48000,//编码码率
	    format: 'pcm',//音频格式，有效值 aac/mp3
	}
	var filesize,tempFilePath
	
	export default {
		
		data() {
			return {
				readOnly: false,
				formats: {},
				
				token:'',
				content:'',
				
				randomFileName:'',
				
				noteTitle:"",
				noteContent:"",
				
				fileName:"",
				isActive: false,
				AIAssistInput:'',
			}
		},
		
		onLoad(option) {
			// #ifndef MP-BAIDU 
			uni.loadFontFace({
				
			})
			// #endif
			
			let that = this;
			uni.getStorage({
			    key:'expires_in',
			    success(res){
			        console.log("缓存中有access_token")
			        console.log("token失效时间：",res.data)
			        const newT = new Date().getTime();
			        // 用当前时间和存储的时间判断，token是否已过期
			        if (newT > parseInt(res.data)) {
			            console.log("token过期，重新获取token")
			            that.getToken();
			        } else {
			            console.log("获取本地缓存的token")
			            that.token = uni.getStorageSync('access_token');
			        }
			    },fail(){
			        console.log("缓存中没有access_token")
			        that.getToken();
			    }
			});
			this.getTokenAI();
			this.randomFileName = generateRandomName();

			let tmp = option.FileName.split("/");
			this.fileName = tmp.pop();
			if(this.fileName !== 'newFile'){	
				uni.getFileSystemManager().readFile({
					
					filePath : option.FileName,
					encoding : 'utf-8',
					position : 0,
				
					success: function(res){
						let tmp = res.data;
						let arr = tmp.split("#<<<<<!*&*!>>>>>#");
						that.noteTitle = arr[0];
						that.noteContent = arr[1];
					},
					fail(res){
						console.error(res);
					}
				})
			}
			else{
				this.noteContent = "<p>对象(What)：</p> <p>场所(Where)：</p> <p>时间和程序(When)：</p> <p>人员(Who)：</p> <p>为什么(Why)：</p> <p>方式(How)：</p>"
			}
		},
		
		methods: {
			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady() {
				// #ifdef MP-BAIDU
				this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editor');
				// #endif

				// #ifdef APP-PLUS || MP-WEIXIN || H5
				
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context;
					
					this.editorCtx.setContents({
						html : this.noteContent
					})
				}).exec();
				
				// #endif
			},
			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},
			
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)
			},
			
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			
			clear() {
				uni.showModal({
					title: '清空编辑器',
					content: '确定清空编辑器全部内容？',
					success: res => {
						if (res.confirm) {
							this.editorCtx.clear({
								success: function(res) {
									console.log("clear success")
								}
							})
						}
					}
				})
			},
			
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				})
			},
			
			insertImage() {
				let that = this;
				uni.chooseImage({
					count: 1,
					success: (res) => {
						uni.uploadFile({
							url: config.baseUrl + '/users/uploadFile', //自己的后端接口（默认发送post请求）
							filePath: res.tempFilePaths[0],
							name: "file", //这里应为自己后端文件形参的名字
							success(res) {
								that.editorCtx.insertImage({
									src: res.data,
									alt: '图像',
									width: 260,
									success: function() {
										console.log('insert image success')
									}
								})
							}
						})
					}
				})
			},
			
			//
			//
			AIAssistExpand(){
				this.isActive = !this.isActive;
			},
			
			AIAssistAsk(){
				let that = this;
				uni.request({
					url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-lite-8k?access_token=' + this.tokenai,
					data: {
						"messages": [
						    {
						        role: "user",
						        content: this.AIAssistInput,
						    }
						],
					},
					method:'POST',
					headers: {
					  'Content-Type': 'application/json',
					}, 
					success(res) {
						let aiRes = res.data.result;
						that.editorCtx.insertText({
							text: aiRes
						})
					}
				})
			},
			
			getTokenAI(){
			  let that=this;
			  let ApiKey='vuUXqkEFYCVUOkA1mvEGXD60';//你自己的apikey
			  let SecretKey='eMFEOC8PUwVyfP71qgp1gTmMEdItGQag';//你自己的SecretKey
			  const url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ApiKey+'&client_secret='+SecretKey
			  uni.request({
			      url:url,
			      method: 'POST',
			      success(res){
			        console.log("创建AIaccess_token成功",res)
						//将access_token存储到storage中
						that.tokenai = res.data.access_token;
					},
			  });
			},
			
			//
			//
			voiceDetectStart(){
				uni.authorize({
				    scope: 'scope.record',
				    success() {
						console.log("录音授权成功");
						recorderManager.start(options);
						recorderManager.onStart(() => {
						console.log('recorder start')
				      });
					  uni.showToast({
						icon:"error",
					  	title:"开始录音",
						duration:1500
					  })
				    },
				    fail() {
				      console.log("录音失败");
				    },
				})
			},
			
			voiceDetectEnd() {
			  let that = this
			  recorderManager.stop();
			  recorderManager.onStop((res) => {
			  console.log('文件路径==', res)
			  tempFilePath= res.tempFilePath;
			  //获取文件长度
			  uni.getFileSystemManager().getFileInfo({
			      filePath: tempFilePath,
			      success: function (res) {
			        filesize = res.size
			        console.log('文件长度', res)
			        that.voiceDetect()
			      }, fail: function (res) {   
			        console.log("读取文件长度错误",res);
			      }
			    }),
				   
				uni.showToast({
				   	icon:"error",
				   	title:"录音结束",
					duration:1000
				})
			  });
			},
			
			getToken(){
			  let that=this;
			  let ApiKey='SwGTHdajqCixYTwnNlUeL7iA';//你自己的apikey
			  let SecretKey='YNF1Sqfk3xqp0fdnj26CltwKIPsOBU3l';//你自己的SecretKey
			  const url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ApiKey+'&client_secret='+SecretKey
			  uni.request({
			      url:url,
			      method: 'POST',
			      success(res){
			        console.log("创建access_token成功",res)
			          //将access_token存储到storage中
			          uni.setStorage({
			            key:'access_token',
			            data:res.data.access_token
			          });
			          var date=new Date().getTime();
			          let time=date+2592000*1000;
			          console.log('三十天后的时间',time);
			          uni.setStorage({
			            key:'expires_in',
			            data:time
			          });
			          that.token = res.data.access_token;
			          },
			  });
			},
			
			voiceDetect(){
			 let that = this;
			 uni.getFileSystemManager().readFile({
			   filePath: tempFilePath,
			   encoding: 'base64',
			   success: function (res) {
			     uni.request({
			       url: 'http://vop.baidu.com/server_api',
			       data: {
			         token: that.token,
			         cuid: "12_56",
			         format: 'pcm',
			         rate: 16000,
			         channel: 1,
			         speech: res.data,
			         len: filesize
			       },
			       headers: {
			         'Content-Type': 'application/json' 
			       }, 
			       method: "post",
			       success: function (res) {
			           if (res.data.result == '') {
			               uni.showModal({
			                 title: '提示',
			                 content: '听不清楚，请重新说一遍！',
			                 showCancel: false
			               })
			               return;
			           }
			           console.log("识别成功==",res.data);
			           that.content = res.data.result;   
					   let detectResult = res.data.result.join();
					   that.editorCtx.insertText({
							text: detectResult
					   })
			       },
			       fail: function (res) {
			         console.log("失败",res);
			       }
			     }); //语音识别结束
			   }
			 })
			},
			
			saveFile(){
				let that = this;
				that.editorCtx.getContents({
					success: function(data){
						that.noteContent = data.html;
						console.log(that.noteContent);
						
						let upath = wx.env.USER_DATA_PATH;
						let draftpath = upath + "/draft";
						uni.getFileSystemManager().mkdir({
							dirPath : draftpath
						});
						
						let saveName = '';
						if(that.fileName !== 'newFile'){
							saveName = that.fileName;
							console.log(saveName);
						}
						else{
							saveName = that.randomFileName + ".note";
							console.log(saveName);
						}
						
						uni.getFileSystemManager().writeFile({
							filePath: draftpath + "/" + saveName,
							data: that.noteTitle + "#<<<<<!*&*!>>>>>#" + data.html + "#<<<<<!*&*!>>>>>#" + 3,
							success(res){
								console.log(that.noteContent);
								console.log(res);
							},
							fail(res){
								console.error(res);
							}
						});
					}
				});
			},
			
			//保存笔记内容到草稿箱
			saveNote(){
				uni.showModal({
					title: '保存内容',
					content: '确定保存当前内容到草稿箱?',
					success: (res) => {
						//需要具体实现
						if (res.confirm) {
							//点击确定
							this.saveFile();
						}
					}
				});
			},
			
			//发布笔记
			publishNote(fileName, type){
				let publishName = '';
				if(this.fileName === 'newFile'){
					publishName = this.randomFileName + ".note";
				}
				else{
					publishName = this.fileName;
				}
				
				
				uni.showModal({
					title: '保存内容',
					content: '确定保存并发布?',
					success: (res) => {
						//需要具体实现
						if (res.confirm) {
							this.saveFile();
							uni.navigateTo({
								url:'/pages/publish/publish?FileName=' + publishName + '&type=' + type
							})
						}
					}
				});
				
			}
		}
	}
</script>

<style scoped>
	@import "./editor-icon.css";

	.page-body {
		height: calc(100vh - var(--window-top) - var(--status-bar-height));
	}

	.wrapper {
		height: 100%;
	}

	.editor-wrapper {
		height: calc(100vh - var(--window-top) - var(--status-bar-height) - 140px);
		background: #fff;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		display: flex;
		box-sizing: content-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
		position: sticky;
	}
	
	.titleInput{
		padding: 4%;
		margin-top: 2%;
		background-color: white;
		font-size: 20px;
		
	}

	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		margin-top: 5px;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}
	
	
	.noteButton{
		display: flex;
		position: fixed;
		bottom: 0;
		width: 100%;
	}
	
	.Btn{
		border-radius: 10px;
		cursor: pointer;
		font-size: 16px;
	}
	
	.searchBox {
		background-color: white;
		padding: 20rpx;
		border-radius: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, .1);
		margin-bottom: 5%;
		overflow: hidden;
		transition-duration: 300ms;
		width: 3%; 
		position: fixed; 
		top: 82%; 
		left: 82%; 
		z-index: 98; 
		background-color: 
	}
	
	.searchBox.active{
		left: 10%;
		width: 70%;
	}
</style>
